//
//  CommentViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/17.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentModel.h"
#import "NavBarView.h"
#import "CommentCell.h"
#import "CommentEmptyCell.h"
#import "CommentSectionHeaderView.h"
#import "CommentComposeViewController.h"
#import "CommentRefModel.h"
#import "CommentListModel.h"
#import "CommentModel.h"
#import "NewsDetailExtraModel.h"
#import "JKProgressHUD.h"
#import "NetworkingTool.h"

@interface CommentViewController () <UITableViewDataSource, UITableViewDelegate, CommentCellDelegate>

/** 长评论模型数据 */
@property (nonatomic, strong) NSMutableArray *longCmts;

/** 短评论模型数据 */
@property (nonatomic, strong) NSMutableArray *shortCmts;

/** 所有评论 存储的是长评论集合 + 短评论集合 */
@property (nonatomic, strong) NSArray *cmts;

/** tableView */
@property (nonatomic, weak) UITableView *tableView;

/** 自定义导航条 */
@property (nonatomic, weak) NavBarView *navBarView;

/** 底部视图 */
@property (nonatomic, weak) UIView *bottomView;

/** 遮盖短评视图 */
@property (nonatomic, weak) UIView *coverView;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;
@end

@implementation CommentViewController

/** 记录短评论是否展开 */
static BOOL _shortCmtUnfolded = NO;

static NSString *commentCellID = @"commentCell";
static NSString *commentEmptyCellID = @"commentEmptyCell";

#pragma mark - 懒加载
- (NSArray *)cmts{
    if (!_cmts) {
        _cmts = @[self.longCmts, self.shortCmts];
    }
    return _cmts;
}

- (NSMutableArray *)longCmts{
    if (!_longCmts) {
        _longCmts = [NSMutableArray array];
    }
    return _longCmts;
}

- (NSMutableArray *)shortCmts{
    if (!_shortCmts) {
        _shortCmts = [NSMutableArray array];
    }
    return _shortCmts;
}

- (NavBarView *)navBarView{
    if (!_navBarView) {
        NSString *title = [NSString stringWithFormat:@"%@ 条评论", @(self.extraModel.comments).stringValue];
        NavBarView *navBarView = [NavBarView barViewWithTitle:title showBackTitle:NO];
        navBarView.leftButton = nil;
        [self.view addSubview:navBarView];
        _navBarView = navBarView;
    }
    return _navBarView;
}

#pragma mark - 生命周期
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NetworkingTool sharedNetworkingTool].operationQueue cancelAllOperations];
    [JKProgressHUD dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // tableView
    [self setupTableView];
    
    // 底部视图
    [self setupBottomView];
    
    // 获取评论数据
    [self loadCommentsData];
}

#pragma mark - 初始化
- (void)setupTableView{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, JKNavBarHeight, self.view.width, self.view.height - JKNavBarHeight - 30) style:(UITableViewStylePlain)];
    tableView.backgroundColor = [UIColor clearColor];
    
    tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    tableView.dataSource = self;
    tableView.delegate = self;
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.estimatedRowHeight = 200;
    
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CommentCell class]) bundle:nil] forCellReuseIdentifier:commentCellID];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CommentEmptyCell class]) bundle:nil] forCellReuseIdentifier:commentEmptyCellID];
    
    [self.view addSubview:tableView];
    self.tableView = tableView;
}

// 获取评论数据
- (void)loadCommentsData{
    // 给个提示
    [JKProgressHUD showWithStatus:@"正在加载评论数据"];
    [JKProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeNone)];
    
    [CommentListModel getAllLongCommentsWithNewsID:self.storyID complete:^(NSMutableArray *longCmts) {
        
        self.longCmts = longCmts;
        
        [CommentListModel getAllShortCommentsWithNewsID:self.storyID complete:^(NSMutableArray *shortCmts) {
            self.shortCmts = shortCmts;
            self.cmts = @[self.longCmts, self.shortCmts];
            [self.tableView reloadData];
            [JKProgressHUD dismiss];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.navBarView.title = [NSString stringWithFormat:@"%@ 条评论", @(self.longCmts.count + self.shortCmts.count).stringValue];
            });
        }];
    }];
}

- (void)setupBottomView{
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = JKColor(52, 53, 53);
    bottomView.frame = CGRectMake(0, JKScreenH - 30, JKScreenW, 30);
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    // 返回按钮
    UIButton *backBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [backBtn setImage:[UIImage imageNamed:@"Back_White"] forState:(UIControlStateNormal)];
    [backBtn setImage:[UIImage imageNamed:@"Back"] forState:(UIControlStateHighlighted)];
    backBtn.frame = CGRectMake(5, 0, 30, 30);
    [backBtn addTarget:self action:@selector(backButtonClick) forControlEvents:(UIControlEventTouchUpInside)];
    [bottomView addSubview:backBtn];
    
    // 分割线
    UIView *sepLineView = [[UIView alloc] init];
    sepLineView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.2];
    sepLineView.frame = CGRectMake(35, 0, 1, 30);
    [bottomView addSubview:sepLineView];
    
    // 写点评
    UIButton *writeCmtBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    writeCmtBtn.frame = CGRectMake(36, 0, JKScreenW - 36, 30);
    [writeCmtBtn setImage:[UIImage imageNamed:@"Comment_Icon_Compose"] forState:(UIControlStateNormal)];
    [writeCmtBtn setTitle:@"写点评" forState:(UIControlStateNormal)];
    [writeCmtBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [writeCmtBtn setTitleColor:[UIColor darkGrayColor] forState:(UIControlStateHighlighted)];
    writeCmtBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    
    [writeCmtBtn addTarget:self action:@selector(writeCmtBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
    
    [bottomView addSubview:writeCmtBtn];
}

#pragma mark - 按钮点击
- (void)writeCmtBtnClick{
    CommentComposeViewController *vc = [[CommentComposeViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)backButtonClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cmts.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ((section == 0) && (self.longCmts.count == 0)) {
        return 1;
        
    }else if (section == 0){
        return [self.cmts[section] count];
        
    }else{
        return _shortCmtUnfolded ? [self.cmts[section] count] : 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ((indexPath.section == 0) && (self.longCmts.count == 0)) { // 没有长评论
        CommentEmptyCell *cell = [tableView dequeueReusableCellWithIdentifier:commentEmptyCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // 切换皮肤
        if ([self.currentSkinModel isEqualToString:JKDaySkinModelValue]) {
            [cell changeToDaySkin];
        }else{
            [cell changeToNightSkin];
        }
        return cell;
    }
    
    CommentModel *cmtModel = self.cmts[indexPath.section][indexPath.row];
    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:commentCellID];
    
    if (cell.delegate == nil) {
        cell.delegate = self;
    }
    
    cell.cmtModel = cmtModel;
    
    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKDaySkinModelValue]) {
        [cell changeToDaySkin];
    }else{
        [cell changeToNightSkin];
    }
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ((indexPath.section == 0) && (self.longCmts.count == 0)) { // 没有长评论
        return JKScreenH - JKNavBarHeight - 30 - 40;
    }
    
    CommentModel *model = self.cmts[indexPath.section][indexPath.row];
    if (model.cmtRefUnfolded) { // 评论展开状态
        CommentCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        CGFloat cmtRefH = [cell calculateRefContentLabelHeightModel:model];
        cmtRefH = (cmtRefH == 0) ? model.cmtRefHeight : cmtRefH;
        return model.cellHeight + cmtRefH - 34;
    }
    
    return model.cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return (self.longCmts.count == 0) ? 0 : 40;
    }
    
    return (self.shortCmts.count == 0) ? 0 : 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    CommentSectionHeaderView *sectionHeaderView  = [CommentSectionHeaderView headerViewWithTableView:tableView];
    
    sectionHeaderView.frame = CGRectMake(0, 0, JKScreenW, 40);
    
    [sectionHeaderView unfoldButtonAddTarget:self action:@selector(unfoldShortCmt:) forControlEvents:(UIControlEventTouchUpInside)];
    
    if ((section == 0) && (self.longCmts.count == 0)) { // 没有长评论，隐藏展开按钮
        sectionHeaderView.unfoldButtonHidden = YES;
        return nil;
        
    }else if (section == 0) { // 长评论，隐藏展开按钮
        sectionHeaderView.unfoldButtonHidden = YES;
        sectionHeaderView.hidden = NO;
        sectionHeaderView.cmtCountText = [NSString stringWithFormat:@"%@ 条长评", @([self.cmts[section] count]).stringValue];
        
    }else{ // 短评论
        // 刷新表格后恢复按钮的选中状态
        [sectionHeaderView resetUnfoldButtonSelected:_shortCmtUnfolded];
        
        sectionHeaderView.unfoldButtonHidden = (self.shortCmts.count == 0);
        sectionHeaderView.hidden = (self.shortCmts.count == 0);
        sectionHeaderView.cmtCountText = [NSString stringWithFormat:@"%@ 条短评", @([self.cmts[section] count]).stringValue];
    }
    
    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKDaySkinModelValue]) {
        [sectionHeaderView changeToDaySkin];
    }else{
        [sectionHeaderView changeToNightSkin];
    }
    
    return sectionHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && self.longCmts.count < 1) return;
    // 取出选中的cell
    CommentCell *cell = (CommentCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    CommentModel *comment = self.cmts[indexPath.section][indexPath.row];
    
    // UIMenuController
    if (!comment.isMenuAdded) {
        comment.menu = [UIMenuController sharedMenuController];
        comment.isMenuAdded = YES;
    }
    cell.selected = ![UIMenuController sharedMenuController].isMenuVisible;
    // 如果menu已经显示了，再次点击要隐藏
    if (comment.menu.isMenuVisible) {
        // 隐藏menu
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
        return;
    }
    
    // 让cell成为第一响应者。只要卸任第一响应者，menu就会消失
    [cell becomeFirstResponder];
    
    // 自定义item
    UIMenuItem *zan = [[UIMenuItem alloc] initWithTitle:((comment.isLiked) ? @"取消赞同" : @"赞同" ) action:@selector(zan:)];
    UIMenuItem *report = [[UIMenuItem alloc] initWithTitle:@"举报" action:@selector(report:)];
    UIMenuItem *copy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyText:)];
    UIMenuItem *respond = [[UIMenuItem alloc] initWithTitle:@"回复" action:@selector(respond:)];
    comment.menu.menuItems = @[zan, report, copy, respond];
    
    // 让menu显示在cell中间
    CGRect rect = CGRectMake(0, cell.height * 0.5, cell.width, cell.height * 0.5);
    [comment.menu setTargetRect:rect inView:cell];
    [comment.menu setMenuVisible:YES animated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    // 隐藏menu
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
}

#pragma mark - UIMenuController点击处理
// 赞同
- (void)zan:(UIMenuController *)menu{
    // 获取选中的行
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    
    // 获取选中行对应的模型，取得评论的内容
    CommentModel *comment = self.cmts[indexPath.section][indexPath.row];
    comment.isLiked = !comment.isLiked;
    comment.likes = (comment.isLiked) ? comment.likes + 1 : comment.likes - 1;
    
    CommentCell *cell = (CommentCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    
    // 取出选中的cell
    [cell zanClick];
}

// 回复
- (void)respond:(UIMenuController *)menu{
    // 获取选中的行
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    // 获取选中行对应的模型，取得评论的内容
    CommentModel *comment = self.cmts[indexPath.section][indexPath.row];;
    CommentComposeViewController *vc = [[CommentComposeViewController alloc] init];
    vc.navTitle = comment.author;
    [self presentViewController:vc animated:YES completion:nil];
}

// 复制
- (void)copyText:(UIMenuController *)menu{
    // 获取选中的行
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    CommentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    // 获取选中行对应的模型，取得评论的内容
    CommentModel *comment = self.cmts[indexPath.section][indexPath.row];
    
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    board.string = comment.content;
    [JKProgressHUD showSuccessWithStatus:@"复制成功！"];
}

// 举报
- (void)report:(UIMenuController *)menu{
    // 获取选中的行
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    CommentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    
    UIAlertController *alerVc = [UIAlertController alertControllerWithTitle:nil message:@"太好了 让我们一起净化评论区" preferredStyle:(UIAlertControllerStyleAlert)];
    
    [alerVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:nil]];
    [alerVc addAction:[UIAlertAction actionWithTitle:@"确认举报" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alerVc animated:YES completion:nil];
}

#pragma mark - 短评论是否展开
- (void)unfoldShortCmt:(UIButton *)button{
    _shortCmtUnfolded = !_shortCmtUnfolded;
    // 长评论最后一个cell的索引
    NSIndexPath *lastLongCmtIndexPath = (self.longCmts.count > 0) ? [NSIndexPath indexPathForRow:self.longCmts.count - 1 inSection:0] : [NSIndexPath indexPathForRow:0 inSection:0];
    CGRect lastLongCmtRect = [self.tableView rectForRowAtIndexPath:lastLongCmtIndexPath];
    CGRect firstLongCmtRect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
    // 收起
    if (!_shortCmtUnfolded) {
        if (CGRectGetMaxY(lastLongCmtRect) - firstLongCmtRect.origin.y <= self.tableView.height - 40) {
            [self.tableView reloadSections:indexSet withRowAnimation:(UITableViewRowAnimationAutomatic)];
            return;
        };
        
        [self.tableView reloadSections:indexSet withRowAnimation:(UITableViewRowAnimationAutomatic)];
        [self.tableView scrollToRowAtIndexPath:lastLongCmtIndexPath atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
        return;
    }
    
    // 展开
    [self.tableView reloadData];
    // 第二组第一个cell的frame
    CGRect firstShortCmtRect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1]];
    // 第二组最后cell的frame
    CGRect lastShortCmtRect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForItem:self.shortCmts.count - 1 inSection:1]];
    
    // 短评的总高度
    CGFloat shortCmtHeight = CGRectGetMaxY(lastShortCmtRect) - firstShortCmtRect.origin.y;
    
    // 短评论的总高度小于中间显示区域的高度
    if (shortCmtHeight <= self.tableView.height - 40) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.shortCmts.count - 1 inSection:1] atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
        return;
    }
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1] atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
}

// plain不悬停方法
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    CGFloat sectionHeaderHeight = 40;
//    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
//        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//
//    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
//        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//    }
//}

#pragma mark - <CommentCellDelegate>
/** 展开和收起引用评论 */
- (void)commentCell:(CommentCell *)cell didClickUnfoldButton:(UIButton *)button{
    // 隐藏menu
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    CommentModel *model = self.cmts[indexPath.section][indexPath.row];
    
    model.cmtRefUnfolded = button.selected;
    // _cmtRefUnfoldBtnHidden = NO;
    
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    self.currentSkinModel = currentSkinModel;
    // 隐藏menu
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.view.backgroundColor = JKNightSkinColor;
        [self.navBarView changeToNightSkin];
        
    }else{ // 日间模式
        [self.navBarView changeToDaySkin];
        self.view.backgroundColor = JKGlobalBgColor;
    }
    
    [self.tableView reloadData];
}

- (void)dealloc{
    [self.longCmts removeAllObjects];
    [self.shortCmts removeAllObjects];
    
    // 细节问题。。
    /** 记录短评论是否展开 */
    _shortCmtUnfolded = NO;
}
@end
